package cn.springcloud.fix.demo.thread;

import lombok.Data;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReadWriteTest2 {

    public static void main(String[] args) {
        Unng unng = new Unng();
        new Thread(new ReadThread(unng)).start();
        new Thread(new WriteThread(unng)).start();
    }

    static class ReadThread implements Runnable {

        private Unng unng;

        public ReadThread(Unng unng) {
            this.unng = unng;
        }

        @Override
        public void run() {
            while (unng.content < 100) {
                try {
                    unng.lock.lock();
                    if (!unng.readAble) {
                        try {
                            unng.condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("读了：" + unng.content);
                    unng.readAble = false;
                    unng.condition.signal();
                } finally {
                    unng.lock.unlock();
                }
            }
        }
    }

    static class WriteThread implements Runnable {

        private Unng unng;

        public WriteThread(Unng unng) {
            this.unng = unng;
        }

        @Override
        public void run() {
            while (unng.content < 100) {
                try {
                    unng.lock.lock();
                    if (unng.readAble) {
                        try {
                            unng.condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    unng.content++;
                    System.out.println("写了：" + unng.content);
                    unng.readAble = true;
                    unng.condition.signal();
                } finally {
                    unng.lock.unlock();
                }
            }
        }
    }

    @Data
    static class Unng {
        public Lock lock = new ReentrantLock();
        public Condition condition = lock.newCondition();
        private boolean readAble;
        private int content;
    }
}
